Popular Searches
Popular Course Categories
Popular Courses

Understanding DispatcherServlet and Request Processing

Understanding DispatcherServlet and Request Processing

Spring MVC and Enterprise Web Development

Understanding DispatcherServlet and Request Processing in Spring MVC

Course: Advanced Java Training

Topic: Understanding DispatcherServlet and Request Processing

Course Link: Advanced Java Training at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to DispatcherServlet

DispatcherServlet is the central front controller in the Spring MVC framework. It receives incoming HTTP requests and coordinates their processing by identifying the appropriate controller, invoking the required application logic, and preparing the response for the client.

In a typical Spring MVC application, a browser or client sends a request to the web server. The request reaches the DispatcherServlet, which consults Spring MVC components to determine how the request should be handled. The controller processes the request, may call service and repository layers, and returns a result. Depending on the application, the result may be a rendered view, JSON data, XML, a file, or another HTTP response.

The DispatcherServlet follows the Front Controller design pattern. Instead of each controller or page independently managing the entire request lifecycle, requests are routed through a central component that coordinates common web-processing responsibilities.

Learning Objectives

  • Understand the purpose of DispatcherServlet in Spring MVC.
  • Learn the Front Controller design pattern.
  • Understand how HTTP requests reach Spring controllers.
  • Explore handler mappings, handler adapters, and view resolvers.
  • Learn how request parameters and request bodies are processed.
  • Understand the difference between returning a view and returning response data.
  • Learn how exceptions and HTTP responses are handled.
  • Identify common request-processing errors and their solutions.

2. What Is the Front Controller Design Pattern?

The Front Controller design pattern introduces a central entry point for processing requests in a web application. The front controller receives requests and delegates work to specialized components instead of implementing every business operation itself.

In Spring MVC, DispatcherServlet acts as the front controller. It coordinates routing, controller invocation, data conversion, view resolution, and exception handling through the Spring MVC infrastructure.

Responsibilities of a Front Controller

  • Receive incoming HTTP requests.
  • Coordinate request routing to appropriate handlers.
  • Invoke the selected controller through the configured infrastructure.
  • Support processing of request parameters and request bodies.
  • Coordinate view rendering when a view-based response is required.
  • Delegate exception handling to configured exception resolvers.
  • Help provide a consistent request-processing structure.

Benefits of the Front Controller Pattern

Benefit Explanation
Centralized processing Requests pass through a common entry point.
Separation of concerns Routing and web infrastructure remain separate from business logic.
Maintainability Common request-processing behavior can be configured centrally.
Extensibility Interceptors, converters, exception handlers, and other components can be integrated into request processing.
Consistent responses Applications can apply consistent response formats and error-handling rules.

3. Main Components Involved in Spring MVC Request Processing

DispatcherServlet coordinates several components. Each component has a specific responsibility in the request lifecycle.

Component Responsibility
DispatcherServlet Coordinates the overall Spring MVC request lifecycle.
HandlerMapping Finds the handler that matches an incoming request.
HandlerAdapter Invokes the selected handler using the appropriate invocation mechanism.
Controller Handles the web request and coordinates application-level operations.
Service layer Contains application and business logic.
Repository or DAO Handles data access, where required.
HttpMessageConverter Reads request bodies and writes response bodies in supported formats such as JSON.
ViewResolver Resolves a logical view name to a view implementation.
View Renders a response for view-based requests.
HandlerInterceptor Provides hooks around handler execution for cross-cutting web concerns.
HandlerExceptionResolver Helps translate exceptions into appropriate web responses.

4. Overall Request Processing Flow

When a client sends a request to a Spring MVC application, the request passes through several stages. The exact flow depends on the response type and application configuration.

  1. Client sends a request: A browser, mobile app, or API client sends an HTTP request.
  2. Servlet container receives it: The web server or servlet container routes the request to the configured servlet mapping.
  3. DispatcherServlet receives the request: It begins coordinating Spring MVC request processing.
  4. HandlerMapping identifies a handler: Spring finds a controller method or other handler matching the request.
  5. Interceptors run as configured: Pre-processing hooks may execute before the handler.
  6. HandlerAdapter invokes the handler: The selected controller method is called through the appropriate adapter.
  7. Request data is resolved: Parameters, path variables, headers, and request bodies are bound to method arguments.
  8. Controller executes application logic: It may call services and repositories to process the request.
  9. Return value is processed: Spring determines whether the result represents a view, response body, or another supported return type.
  10. Response is produced: A view may be rendered or a message converter may write data such as JSON.
  11. Response is sent to the client: The servlet container returns the HTTP status, headers, and response body.

Request Flow Diagram

Client / Browser
       |
       v
Servlet Container
       |
       v
DispatcherServlet
       |
       v
HandlerMapping
       |
       v
HandlerAdapter
       |
       v
Controller
       |
       v
Service Layer
       |
       v
Repository / Database
       |
       v
Controller Return Value
       |
       +------------------------------+
       |                              |
       v                              v
View Resolution                 Message Converter
       |                              |
       v                              v
HTML / View Response            JSON / Text / Data Response
       |                              |
       +---------------+--------------+
                       |
                       v
                 HTTP Response
                       |
                       v
                  Client

This diagram represents a simplified flow. Some requests do not access a database, and REST endpoints commonly use message converters rather than view resolution.

```html

5. Registering DispatcherServlet

The DispatcherServlet must be registered with the servlet container and mapped to the URL patterns it should handle. Traditional Spring MVC applications may use Java-based servlet initialization or web.xml. Spring Boot applications usually configure and register the servlet automatically through their web application setup.

5.1 Traditional XML Configuration Using web.xml

The following example demonstrates how a traditional servlet-based Spring MVC application can declare and map the dispatcher servlet.

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         version="6.0">
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

The servlet mapping determines which requests reach the dispatcher. The exact deployment descriptor version must match the servlet container and framework version. In older applications, the XML namespace and version may differ.

5.2 Java-Based Servlet Registration

For applications that use traditional servlet-container deployment without Spring Boot, Spring supports programmatic servlet initialization.

import org.springframework.web.servlet.support
    .AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

This initializer separates the root application configuration from the servlet-specific configuration. The root context commonly contains services and repositories, while the servlet context commonly contains web-related components such as controllers and MVC configuration.

5.3 DispatcherServlet in Spring Boot

In a standard Spring Boot web application, developers generally do not need to register DispatcherServlet manually. Spring Boot configures the servlet infrastructure when the required Spring MVC dependencies are present.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

For additional information, see the official Spring MVC DispatcherServlet documentation.

6. Understanding HandlerMapping

HandlerMapping identifies the handler that should process an incoming request. In annotation-based Spring MVC applications, a controller method can be mapped using annotations such as @RequestMapping, @GetMapping, and @PostMapping.

The mapping process considers relevant request details, which may include the URL path, HTTP method, request parameters, headers, and content types. If Spring finds a matching handler, the dispatcher continues processing through an appropriate handler adapter.

Example Controller Mapping

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/products")
public class ProductController {

    @GetMapping
    @ResponseBody
    public String getProducts() {
        return "Product list";
    }
}

When the application receives a GET request for /products, Spring can map it to the getProducts() method, provided the controller is registered and the request matches the configured servlet mapping.

Common Request Mapping Annotations

Annotation Purpose Typical Use
@RequestMapping Defines a general request mapping. Mapping paths and request conditions.
@GetMapping Maps HTTP GET requests. Retrieving data or displaying a page.
@PostMapping Maps HTTP POST requests. Submitting forms or creating resources.
@PutMapping Maps HTTP PUT requests. Replacing or updating a resource.
@PatchMapping Maps HTTP PATCH requests. Partially updating a resource.
@DeleteMapping Maps HTTP DELETE requests. Deleting a resource.

7. Understanding HandlerAdapter

A HandlerAdapter invokes a handler selected by the HandlerMapping. It allows the dispatcher servlet to work with different handler types without needing to know the implementation details of every handler.

For annotated controllers, Spring MVC commonly uses RequestMappingHandlerAdapter. It supports method argument resolution, data binding, validation integration, and return-value processing.

What Happens During Handler Invocation?

  • Spring identifies the mapped controller method.
  • It resolves method arguments such as path variables, request parameters, headers, and request bodies.
  • It performs configured data binding and conversion.
  • It invokes the controller method.
  • It processes the returned value according to the return type and applicable annotations.

Developers normally do not create a handler adapter manually. Spring MVC supplies the required infrastructure through its standard configuration.

8. Processing Request Parameters

Request parameters commonly appear in the query string of a URL or are submitted through form data. Spring MVC provides @RequestParam to bind request parameters to controller method arguments.

Example URL

http://localhost:8080/products?category=books&page=2

Controller Example

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ProductSearchController {

    @GetMapping("/search")
    @ResponseBody
    public String searchProducts(
            @RequestParam String category,
            @RequestParam(defaultValue = "1") int page) {

        return "Category: " + category + ", Page: " + page;
    }
}

A request such as /search?category=books&page=2 supplies the value books for the category and 2 for the page. The default value is used when the page parameter is absent.

Important @RequestParam Options

Option Description
value or name Specifies the request parameter name.
required Controls whether the parameter must be present; it defaults to true.
defaultValue Provides a fallback value when the parameter is missing or empty.

9. Processing Path Variables

Path variables represent values embedded directly in the URL path. They are commonly used when a request identifies a particular resource by an ID or another unique value.

Example URL

GET /products/105

Controller Example

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ProductDetailsController {

    @GetMapping("/products/{id}")
    @ResponseBody
    public String getProduct(@PathVariable Long id) {
        return "Requested product ID: " + id;
    }
}

For a request to /products/105, Spring binds the path segment 105 to the id argument, converting it to a Long when possible. Invalid values may cause a conversion or binding error.

@RequestParam vs @PathVariable

Feature @RequestParam @PathVariable
Location Query string or request parameters. URL path.
Example /products?page=2 /products/105
Typical purpose Filtering, sorting, pagination, and optional criteria. Identifying a specific resource.

10. Reading Request Bodies with @RequestBody

When a client sends JSON or another supported data format in the HTTP request body, Spring MVC can use @RequestBody to deserialize the body into a Java object. This processing is generally performed by a suitable HttpMessageConverter.

Java Model

public class ProductRequest {
    private String name;
    private double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

REST Controller

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductApiController {

    @PostMapping("/api/products")
    public ResponseEntity<String> createProduct(
            @RequestBody ProductRequest request) {

        String result = "Received product: " + request.getName();
        return ResponseEntity.ok(result);
    }
}

Example JSON Request

{
    "name": "Keyboard",
    "price": 1499.00
}

The client should send an appropriate content type, commonly application/json. A JSON converter, such as one backed by Jackson when configured, reads the request body and maps it to the Java object. Invalid JSON or incompatible data types can cause a request-processing error.

11. Returning Data with @ResponseBody and @RestController

Spring MVC supports both view-based responses and direct response-body responses. The return value's interpretation depends on the controller type, annotations, and configured return-value handlers.

Using @ResponseBody

@Controller
public class StatusController {

    @GetMapping("/status")
    @ResponseBody
    public String status() {
        return "Application is running";
    }
}

Here, the returned string is written to the HTTP response body instead of being interpreted as a logical view name.

Using @RestController

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HealthController {

    @GetMapping("/api/health")
    public HealthResponse health() {
        return new HealthResponse("UP");
    }

    public record HealthResponse(String status) {}
}

@RestController combines @Controller and @ResponseBody behavior. When a suitable message converter is available, a returned object can be serialized into JSON or another negotiated response format.

12. View Resolution and Model Handling

In traditional Spring MVC applications, a controller may return a logical view name. The dispatcher uses a ViewResolver to locate the actual view template or view implementation. The model carries data that the view needs to render the response.

Controller Returning a View

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/home")
    public String showHome(Model model) {
        model.addAttribute("message", "Welcome to Spring MVC");
        return "home";
    }
}

The returned value home is a logical view name. A configured view technology, such as Thymeleaf or JSP, can resolve it to a template or page. The model attribute message is made available to the view.

Example Thymeleaf Template

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
    <h1 th:text="${message}">Welcome</h1>
</body>
</html>

The actual template location depends on the application's Thymeleaf configuration and defaults. If a view cannot be found, check the template directory, file name, and configured view resolver.

13. HTTP Message Converters

HttpMessageConverter implementations read request bodies and write response bodies. They are important in REST APIs because controllers often receive JSON and return JSON rather than rendering server-side HTML views.

Converter Category Typical Purpose
String converter Reads or writes text content.
JSON converter Converts JSON to Java objects and Java objects to JSON.
Byte array converter Handles binary content such as image or file data.
Form converter Handles supported form data formats.
XML converter Handles XML when a suitable implementation is configured.

Converter selection depends on factors such as the declared Java type, request content type, acceptable response media types, and installed converters. If no suitable converter is available, request reading or response writing may fail.

14. Handler Interceptors in Request Processing

A HandlerInterceptor provides hooks before and after controller execution. Interceptors are useful for request logging, timing, and certain cross-cutting web concerns. They are not a replacement for servlet filters or a complete security framework.

Example Interceptor

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class RequestLoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {

        System.out.println("Request path: " + request.getRequestURI());
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            Exception exception) {

        System.out.println("Response status: " + response.getStatus());
    }
}

The preHandle method runs before the handler. Returning true allows the execution chain to continue, while returning false stops it. The afterCompletion method is used for cleanup or logging after request completion when applicable.

Registering the Interceptor

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestLoggingInterceptor())
                .addPathPatterns("/api/**");
    }
}

This configuration applies the interceptor to paths matching /api/**. In larger applications, the interceptor can be registered as a Spring bean and injected where appropriate.

15. Exception Handling During Request Processing

Exceptions may occur during handler selection, argument binding, validation, controller execution, service calls, or response conversion. Spring MVC uses configured exception-resolution mechanisms to determine how to translate supported exceptions into an HTTP response or an error view.

Using @ExceptionHandler

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleBadRequest(
            IllegalArgumentException exception) {

        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body("Invalid request: " + exception.getMessage());
    }
}

@RestControllerAdvice enables shared exception handling for REST controllers. The example maps an IllegalArgumentException to HTTP 400. In production, error responses should avoid exposing stack traces, internal implementation details, or sensitive information.

Common HTTP Status Codes

Status Code Meaning Example
200 OK Request succeeded. Successfully retrieving product details.
201 Created A resource was created. Creating a product through a REST endpoint.
400 Bad Request The request is invalid or cannot be processed as supplied. Malformed input or invalid parameters.
401 Unauthorized Authentication is required or invalid. Missing or invalid authentication credentials.
403 Forbidden The request is not permitted. An authenticated user lacks required permission.
404 Not Found The requested resource or route is not found. Unknown product ID or unmapped path.
500 Internal Server Error An unexpected server-side error occurred. An unhandled application failure.

16. Filters vs Interceptors

Filters and interceptors both participate in web request processing, but they operate at different levels. A servlet filter is part of the servlet container's filter chain, while a Spring MVC interceptor operates around handler execution within the MVC infrastructure.

Feature Servlet Filter Spring MVC Interceptor
Execution level Servlet container. Spring MVC handler execution.
Request scope Can apply before the dispatcher and across mapped servlet requests. Associated with Spring MVC handler processing.
Typical use Request wrapping, character encoding, and general servlet-level processing. Handler-specific logging, timing, and request-related checks.
Handler awareness Does not normally receive the selected Spring MVC handler. Can receive the selected handler object.
Security note Security filters can form part of the security chain. Should not be treated as a complete substitute for security controls.

17. Request Processing and Validation

Incoming request data should be validated before it is used in business operations. Spring MVC can integrate with Jakarta Bean Validation to check fields such as names, email addresses, prices, and identifiers.

Example Request Model

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;

public class ProductCreateRequest {

    @NotBlank
    private String name;

    @Positive
    private double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

Validating the Request Body

import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductCreationController {

    @PostMapping("/api/products/validate")
    public ResponseEntity<String> create(
            @Valid @RequestBody ProductCreateRequest request) {

        return ResponseEntity.ok(
                "Validated product: " + request.getName());
    }
}

For validation to work, the appropriate validation implementation must be present in the application. Invalid input can be handled using a global exception handler to return a clear and consistent client error response.

18. Common DispatcherServlet Errors and Troubleshooting

Error or Symptom Possible Cause Recommended Solution
404 Not Found No matching handler or incorrect servlet mapping. Check the URL, HTTP method, controller registration, and servlet mapping.
405 Method Not Allowed The URL exists, but the HTTP method does not match a handler mapping. Verify whether the endpoint expects GET, POST, PUT, PATCH, or DELETE.
400 Bad Request Missing required parameters, failed type conversion, invalid JSON, or validation errors. Inspect request data, content type, parameter names, and validation rules.
500 Internal Server Error An unhandled exception or server-side failure. Review application logs and configure appropriate exception handling.
No handler found Controller is not registered or request conditions do not match. Check component scanning and mapping annotations.
View not found Logical view name does not resolve to an available template. Verify the template location, name, view resolver, and view technology.
JSON conversion failure Invalid JSON, missing converter, or incompatible Java types. Check request body syntax, media types, and converter dependencies.
Null dependency in controller Object was created manually or dependency injection was not configured. Use Spring-managed beans and verify constructor injection.
Interceptor not executed Interceptor was not registered or path patterns do not match. Check the MVC configuration and registered path patterns.
Request reaches the wrong endpoint Overlapping mappings or incorrect request conditions. Review mapping paths, HTTP methods, headers, and parameter conditions.

19. Best Practices for DispatcherServlet and Request Processing

  • Keep controller methods focused on handling HTTP concerns and coordinating application services.
  • Place business rules in the service layer rather than embedding them in controllers.
  • Use constructor injection for required controller dependencies.
  • Choose clear and consistent URL patterns and HTTP methods.
  • Use request and response DTOs to separate API contracts from persistence entities.
  • Validate untrusted request data before performing business operations.
  • Return meaningful HTTP status codes and consistent error response formats.
  • Use global exception handling for errors that need consistent treatment across controllers.
  • Use interceptors for appropriate MVC-level concerns and filters for servlet-level concerns.
  • Avoid exposing stack traces, internal paths, credentials, or sensitive application details in responses.
  • Log enough information to diagnose failures without recording confidential data.
  • Write integration tests for important request mappings and error scenarios.

20. Practical Project: Product Management with Spring MVC

Create a small product management application to practise the complete request-processing lifecycle.

Project Requirements

  1. Create a Spring Boot project with the Spring Web dependency.
  2. Create a Product model or response DTO.
  3. Create a ProductService class to handle product-related operations.
  4. Create a ProductController with endpoints for listing, viewing, creating, and deleting products.
  5. Use @PathVariable to identify a product by ID.
  6. Use @RequestParam for search and pagination parameters.
  7. Use @RequestBody to receive product creation data in JSON format.
  8. Use @Valid with suitable validation constraints.
  9. Return JSON responses through @RestController.
  10. Add a global exception handler using @RestControllerAdvice.
  11. Register a logging interceptor for selected API paths.
  12. Test successful requests and error cases using a browser or API client.

Suggested Endpoint Design

HTTP Method Endpoint Purpose
GET /api/products Retrieve the product list.
GET /api/products/{id} Retrieve one product by ID.
POST /api/products Create a product.
DELETE /api/products/{id} Delete a product by ID.
GET /api/products/search?name=keyboard Search products using a request parameter.

Expected Learning Outcomes

  • Understand how a request reaches the dispatcher servlet.
  • Configure controller mappings and handler methods.
  • Bind request parameters, path variables, and JSON request bodies.
  • Return structured HTTP responses.
  • Use validation and exception handling to manage invalid requests.
  • Understand how interceptors participate in request processing.

21. Interview Questions and Answers

Q1. What is DispatcherServlet in Spring MVC?

Answer: It is the central front controller that coordinates HTTP request processing by finding the appropriate handler, invoking it through a handler adapter, and managing the resulting view or response.

Q2. What is the Front Controller design pattern?

Answer: It is a design pattern in which requests pass through a central controller that coordinates routing and shared processing responsibilities.

Q3. What is the role of HandlerMapping?

Answer: It identifies the handler that matches the incoming request based on the configured mapping conditions.

Q4. What is the role of HandlerAdapter?

Answer: It invokes the selected handler using the appropriate invocation mechanism and supports processing method arguments and return values.

Q5. What is the difference between @Controller and @RestController?

Answer: @Controller is commonly used for MVC controllers that return view names. @RestController combines @Controller and @ResponseBody behavior, so handler return values are written to the response body through suitable return-value handling.

Q6. What is the purpose of ViewResolver?

Answer: It resolves a logical view name returned by a controller to a view implementation or template that can render the response.

Q7. What is the difference between @RequestParam and @PathVariable?

Answer: @RequestParam binds request parameters, commonly from a query string, while @PathVariable binds a value embedded in the URL path.

Q8. What does @RequestBody do?

Answer: It allows Spring MVC to read the HTTP request body and convert it into a Java object using a suitable message converter.

Q9. How does Spring MVC return JSON?

Answer: A REST controller can return an object that is serialized by a suitable HttpMessageConverter, commonly a JSON converter when one is configured.

Q10. What is a HandlerInterceptor?

Answer: It provides hooks around Spring MVC handler execution, allowing tasks such as request logging and timing to be performed before or after controller processing.

Q11. What is the difference between a filter and an interceptor?

Answer: A filter operates in the servlet container's filter chain, while an interceptor operates within Spring MVC's handler-processing infrastructure.

Q12. How can exceptions be handled globally?

Answer: A class annotated with @ControllerAdvice or @RestControllerAdvice can define shared exception-handling methods using @ExceptionHandler.

Q13. Why might a controller endpoint return 404?

Answer: The requested path may be incorrect, the controller may not be registered, the servlet mapping may not match, or no handler may satisfy the request conditions.

Q14. What happens when a controller returns a view name?

Answer: For a view-based controller, Spring generally uses a view resolver to locate the view and renders it with the model data, unless another return-value mechanism applies.

Q15. Does every DispatcherServlet request need to access a database?

Answer: No. The controller may return static information, calculate a result, call an external service, render a page, or produce a response without accessing a database.

22. Quick Revision Checklist

  • DispatcherServlet is the central front controller in Spring MVC.
  • HandlerMapping finds the handler for a request.
  • HandlerAdapter invokes the selected handler.
  • Controllers process web requests and coordinate application logic.
  • @RequestParam reads request parameters.
  • @PathVariable reads values embedded in URL paths.
  • @RequestBody reads request data through a message converter.
  • @ResponseBody writes the handler return value to the response body.
  • @RestController combines controller and response-body behavior.
  • ViewResolver resolves logical view names for view-based responses.
  • HandlerInterceptor provides hooks around handler execution.
  • @RestControllerAdvice supports shared REST exception handling.
  • Request validation helps prevent invalid data from entering business operations.
  • Correct servlet mappings, controller registration, and HTTP methods are essential for successful routing.

23. Conclusion

DispatcherServlet is a fundamental component of Spring MVC because it coordinates the processing of incoming HTTP requests. It works with handler mappings, handler adapters, controllers, message converters, view resolvers, interceptors, and exception resolvers to produce an appropriate response.

Understanding the complete request lifecycle helps developers build better MVC applications and REST APIs. By using clear controller mappings, constructor injection, request validation, structured responses, and centralized exception handling, developers can create web applications that are easier to test, maintain, and troubleshoot.

To learn more about Java and Spring development, explore Advanced Java Training at JustAcademy, register for a course demo, or visit the JustAcademy official website.

Previous Next
whatsapp